
import pandas as pd
from pyecharts.charts import Bar, Tab, Line, Page, Grid, Timeline
from pyecharts import options as opts
# pyecharts==2.0.8


def cal_tztd_index(df):
    area_fill_li = []
    idx_li = [str(s)[:10] for s in df.index.to_list()]
    for i in range(len(idx_li)-1):
        idx_start = idx_li[i]
        idx_end = idx_li[i+1]
        y_diff = df.iloc[:,0][idx_end] - df.iloc[:,0][idx_start]
        x_diff = df.iloc[:,1][idx_end] - df.iloc[:,1][idx_start]
        if y_diff * x_diff > 0:
            area_fill_li.append((idx_start, idx_end))
    tztd_ratio = len(area_fill_li) / (len(idx_li) - 2)
    return area_fill_li, tztd_ratio


def xy_match_same_freq_plot(df_cot, idx_fill, tztd_ratio):
    cols = df_cot.columns.to_list()
    b = Line()
    idx = [str(s)[:10] for s in df_cot.index]
    b.add_xaxis(idx)
    # 确保标签显示
    b.add_yaxis(cols[0], df_cot[cols[0]].to_list(), yaxis_index=0,
                color='black', label_opts=opts.LabelOpts(is_show=False)) # 添加第一条曲线，默认使用左侧y轴
    # 扩展一个右侧的y轴
    b.extend_axis(
        yaxis=opts.AxisOpts(name="特征X", type_="value", position="right")
    )
    # 确保标签显示
    b.add_yaxis(cols[1], df_cot[cols[1]], yaxis_index=1, color='red', label_opts=opts.LabelOpts(is_show=False)) # 添加第二条曲线，指定使用右侧y轴
    b.set_series_opts(
        markarea_opts=opts.MarkAreaOpts(
            data=[opts.MarkAreaItem(x=s) for s in idx_fill],
            itemstyle_opts=opts.ItemStyleOpts(color='pink',opacity=0.1),
        ),
                      )
    # 全局配置项
    b.set_global_opts(
        datazoom_opts=[
            opts.DataZoomOpts(range_start=10, range_end=100),
            opts.DataZoomOpts(type_="inside")
        ],
        title_opts=opts.TitleOpts(title=f"因子关联分析>同涨同跌率:{100*tztd_ratio:.2f}%"),
        yaxis_opts=opts.AxisOpts(name="指标Y"),
        toolbox_opts=opts.ToolboxOpts(),
        tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross", textstyle_opts=opts.TextStyleOpts(color='black')),
        legend_opts=opts.LegendOpts(pos_top="6%", is_show=True, textstyle_opts=opts.TextStyleOpts(color='black'))
    )
    return b


if __name__ == "__main__":
    df_xy = pd.read_excel('df_xy.xlsx', index_col=0)

    idx_fill, tztd_ratio = cal_tztd_index(df_xy)
    b = xy_match_same_freq_plot(df_xy, idx_fill, tztd_ratio)
    b.render('test.html')